package cn.com.yang.algorithm;

import com.alibaba.fastjson.JSONObject;

import cn.com.yang.utils.DateUtil;

import org.apache.commons.codec.digest.DigestUtils;
import org.apache.http.HttpEntity;
import org.apache.http.HttpStatus;
import org.apache.http.ParseException;
import org.apache.http.StatusLine;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.junit.Test;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Base64;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * SHA算法
 * 
 * @author yangyijin
 *
 */
public class SHA1Util {
	public static String encideSHA(String str) {
		MessageDigest shaDigest = null;
		try {
			shaDigest = MessageDigest.getInstance("SHA1");
		} catch (NoSuchAlgorithmException e) {
			e.printStackTrace();
		}
		byte[] barr = null;
		try {
			barr = str.getBytes("UTF-8");
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		byte[] msg5Bytes = shaDigest.digest(barr);
		StringBuffer hexValue = new StringBuffer();
		for (int i = 0; i < msg5Bytes.length; i++) {
			int val = ((int) msg5Bytes[i]) & 0xff;
			if (val < 10) {
				hexValue.append("0");
			}
			hexValue.append(Integer.toHexString(val));
		}
		return hexValue.toString();
	}

	/**
	 * base64字符串
	 */
	public static String enBase64Str(String str) {
		try {
			return Base64.getEncoder().encodeToString(str.getBytes("UTF-8"));
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		return null;
	}

	public static void  httpPost(String url,Map<String,String> headMap,Map<String,String> params) {
		CloseableHttpClient httpclient = HttpClients.createDefault();
		HttpPost httpPost = new HttpPost(url);// 创建httpPost
		httpPost.setHeader("Accept", "application/json");
		httpPost.setHeader("Content-Type", "application/json");
		httpPost.setHeader("X-Auth", headMap.get("X-Auth"));
		httpPost.setHeader("X-Sign", headMap.get("X-Sign"));
		httpPost.setHeader("mac", "application/json");
		StringEntity entity = new StringEntity(JSONObject.toJSONString(params), "utf-8");
		System.out.println(JSONObject.toJSONString(params));
		httpPost.setEntity(entity);
		CloseableHttpResponse response = null;
		try {
			try {
				response = httpclient.execute(httpPost);
			} catch (ClientProtocolException e1) {
				e1.printStackTrace();
			} catch (IOException e1) {
				e1.printStackTrace();
			}
			StatusLine status = response.getStatusLine();
			int state = status.getStatusCode();
			if (state == HttpStatus.SC_OK) {
				HttpEntity responseEntity = response.getEntity();
				try {
					System.out.println(EntityUtils.toString(responseEntity));
				} catch (ParseException | IOException e) {
					e.printStackTrace();
				}
			} else {
				System.out.println("请求返回:" + state + "(" + url + ")");
			}
		} finally {
			if (response != null) {
				try {
					response.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
			try {
				httpclient.close();
			} catch (IOException e) {	
				e.printStackTrace();
			}
		}
	}

	/**
	 * X-Auth 是 使用Base64编码（账号 + 英文冒号 + 时间戳），时间戳是当前系统时间，格式yyyyMMddHHmmss 身份验证信息
	 * X-Sign 是 使用SHA1加密（账号 + 发送授权码 + 时间戳），时间戳与X-Auth中的相同 签名信息 注：发送授权码即消息平台分配的发送密码
	 * Mac 是 校验整个请求体（不含请求头） 消息鉴别码，确保消息的完整性和可靠性 Content-Type 是 application/json
	 * 后端服务仅识别json报文 Accept 否 application/json 后端服务默认响应json，非必填
	 * 
	 * { "msgId": "", "batchName": "直发接口-微信", "bizCode": "DGTZ-KHTZ-0001",
	 * "msgType": 2, "varMap": { "KeyWrd01": "微信直发模板消息", // 模板匹配变量 "KeyWrd02":
	 * "1111111111111111", "KeyWrd03": "11122222222211", "KeyWrd04":
	 * "22223333333333333333333", "KeyWrd05": "111144444444444441", "KeyWrd06":
	 * "22255555555555552", "KeyWrd07": "11666666666666111" }, "scheduleTime": "",
	 * "toList": [ "omDODt21cjfbA0OwXuaGyzQxRKIo" // openId ], "content":"" //留空即可 }
	 * 
	 * @param args
	 */
	public static void main(String[] args) {
		String acctNum = "2120";
		String spex = ":";
		String pass = "QWd4343";
		String nowdate = DateUtil.parseDate(new Date(), "yyyyMMddHHmmss");

		String X_Auth = enBase64Str(acctNum + spex + nowdate);
		System.out.println("X-Auth>>" + X_Auth);
		String X_Sign = encideSHA(acctNum + pass + nowdate);
		System.out.println("X-Sign>>" + X_Sign);
		Map<String,String> headMap = new HashMap();
		headMap.put("X-Auth",X_Auth);
		headMap.put("X-Sign",X_Sign);
		Map<String,String> params = new HashMap();
		params.put("batchName","直发接口-微信");
		params.put("bizCode","");
		params.put("msgType","2");
		httpPost("http://{ip}:30020/api/v3.0/msg/send/direct",headMap,params);
	}
	
	@Test
	public void test0() {
		String str1= DigestUtils.sha1Hex("abc");
		// A9993E364706816ABA3E25717850C26C9CD0D89D
		// a9993e364706816aba3e25717850c26c9cd0d89d
//		String str2 = DigestUtils.sha1Hex("code:dasdasdasd00001:mcdh");
		String str2= SHA1Util.encideSHA("abc");
		System.out.println(str1);
		System.out.println(str2);
	}
	
}
